﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Loader;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NetCoreMvcTest.Utils;
using ServiceReference;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Extensions;
using Newtonsoft.Json;
using NetCoreMvcTest.Filters;

namespace NetCoreMvcTest.Controllers
{
    //[ApiController]
    //[Route("[controller]/[action]")]
    [MyActionFilter]
    public class TestController : Controller
    {
        private readonly IWebHostEnvironment env;

        //static ChannelFactory<Service1Soap> factory = new ChannelFactory<Service1Soap>(new BasicHttpBinding(), new EndpointAddress("http://127.0.0.1:8088/xtserver/Service1.asmx"));

        public TestController(ILogger<TestController> logger, IWebHostEnvironment env)
        {
            Logger = logger;
            this.env = env;
        }

        public ILogger<TestController> Logger { get; }

        public IActionResult TestJson()
        {
            var obj = new { name = "wb", age = 1 };
            var json = "{\"ok\":true}";
            return Json(json);
        }
        private string MapPath(string path)
        {
            if (path.StartsWith("~/"))
            {
                path = path.Substring(2); //.TrimStart(new char[] { '~', '/' }); //path.Replace("~/", "");
            }
            else if (path.StartsWith("/") || path.StartsWith("\\"))
            {
                path = path.Substring(1); //path.TrimStart('/');
            }

            return Path.Combine(env.WebRootPath, path);
        }
        public IActionResult TestPathC()
        {
            var path = MapPath("~/test/21");
            //if (!Directory.Exists(path)) {
            //    Directory.CreateDirectory(path);
            //}
            return Content(path);
        }
        public IActionResult TestPath()
        {
            var evn = ServiceLocator.Instance.GetService<IWebHostEnvironment>();
            var contentPath = evn.ContentRootPath;
            var webroot = evn.WebRootPath;
            var appDomainPath = AppDomain.CurrentDomain.BaseDirectory;
            return Content($"webroot:{webroot}; </br> contentPath:{contentPath};</br> appDomainPath:{appDomainPath};");
        }

        public IActionResult Index()
        {
            //factory.Endpoint.Address = new EndpointAddress("http://127.0.0.1:8088/xtserver/Service1.asmx");
            //var channel = factory.CreateChannel();
            //var result = channel.getczsjAsync("", "", "admin", "admin", "", "", 1).Result;
            Service1SoapClient client = new Service1SoapClient(Service1SoapClient.EndpointConfiguration.Service1Soap);
            client.ChannelFactory.Endpoint.Address = new EndpointAddress("http://localhost:808/xtserver/Service1.asmx");
            var result = client.TestMethodAsync("").Result;
            return Content(result.ToString());
            //Logger.LogDebug("message");
            //return Content("ok");
        }
        public IActionResult TestAssembly()
        {
            string xitong = "测试系统";
            AssemblyLoadContext context = new AssemblyLoadContext($"Plug_{xitong}", true);
            var dllFolderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xitong);
            var dllName = "AssemblyLableOne.dll";
            var dllPath = Path.Combine(dllFolderName, "AssemblyLableOne.dll");

            // var assembly = context.LoadFromAssemblyPath(dllPath); //未加载程序集的引用
            var di = new DirectoryInfo(dllFolderName);
            var excludeFile = "";
            var allReferences = di.GetFiles("*.dll").Where(p => p.Name != excludeFile);


            foreach (var f in allReferences)
            {
                context.LoadFromAssemblyPath(f.FullName);
            }
            var assembly = context.Assemblies.Where(b => b.CodeBase.EndsWith(dllName)).FirstOrDefault();
            var types = assembly.GetTypes();
            var dtType = types.Where(t => t.Name.Equals("DT")).FirstOrDefault();
            string result = "";
            if (dtType != null)
            {
                var obj = Activator.CreateInstance(dtType);
                var method = dtType.GetMethod("GetNameFromId");
                if (method == null)
                {
                    result = "没有找到相应的方法";
                }
                else
                    result = (string)method.Invoke(obj, new[] { "1" });

            }
            //context?.Unload();
            //context = null;
            return Content(result);
        }

        public IActionResult TestUrl()
        {
            var ab = Request.GetDisplayUrl();
            var host = HttpContext.Request.Host.Value;
            return Content($"uri:{ab} -- host:{host}");
        }

        public string TestParam(string username, string password, string token, string eid)
        {
            var json = JsonConvert.SerializeObject(new { username, password, token, eid });
            return json;
        }
        public string TestForm(TestModel testModel) {
            return JsonConvert.SerializeObject(testModel);
        }
        public string TestFromBody([FromBody]TestModel testModel)
        {
            return JsonConvert.SerializeObject(testModel);
        }
        //public string TestParam(TestModel testModel)
        //{
        //    var json = JsonConvert.SerializeObject(testModel);
        //    return json;
        //}
        //[Consumes("application/json")]
        //public string TestParam([FromBody]string json)
        //{
        //    return json;
        //    //return TestParam(new TestModel { username = testModel.username, password = testModel.password, eid = testModel.eid, token = testModel.token });
        //}
        public class TestModel
        {
            public string username { get; set; }
            public string password { get; set; }
            public string eid { get; set; }
            public string token { get; set; }
        }
    }
}